package com.atguigu.gulimall.product.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.product.utils.entity.Ninjia;
import com.atguigu.gulimall.product.utils.entity.ShadowRocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class LoadCoordinate {
    static String jsonStr = "";


    public static void initData() {
        ClassPathResource classPathResourceData = new ClassPathResource("static/source.json");
        if(classPathResourceData.exists()){
            try {
                jsonStr = readFile(classPathResourceData.getInputStream());

            } catch (IOException e) {
                log.error("读取数据");
            }
        }

        JSONObject jsonObject = JSON.parseObject(jsonStr);

        JSONArray jsonArray = jsonObject.getJSONArray("options");

        List<Ninjia> ninjiaList = JSONObject.parseArray(jsonArray.toJSONString(), Ninjia.class);

        List<ShadowRocket> collect = ninjiaList.stream().map(e -> {
            ShadowRocket shadowRocket = new ShadowRocket();
            shadowRocket.setHost(e.getIpAddress());
            shadowRocket.setTitle(e.getLocation().getCountry() + "-" + e.getLocation().getCity());
            return shadowRocket;
        }).collect(Collectors.toList());

        System.out.println(JSON.toJSONString(collect));

    }

    public static String readFile(InputStream inputStream) throws IOException {

        Reader reader = new InputStreamReader(inputStream,"utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();

        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }

        reader.close();

        return sb.toString();
    }

    public static void main(String[] args) {
        initData();
    }
}
